package com.qyhl.webtv.module_user.setting.userinfo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.hawk.Hawk;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.Base64Parse;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.AppConfigConstant;
import com.qyhl.webtv.commonlib.entity.user.UserInfoBean;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.module_user.R;
import com.qyhl.webtv.module_user.R2;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/12/8.
 * 用户信息及修改界面
 */

@Route(path = ARouterPathConstant.USERINFO, extras = ARouterPathConstant.LOGIN_NEEDED)
public class UserInfoActivity extends BaseActivity implements UserInfoContract.UserInfoView {
    @BindView(R2.id.back)
    ImageView back;
    @BindView(R2.id.commit)
    TextView commit;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.head_icon)
    ImageView headIcon;
    @BindView(R2.id.nickname)
    TextView nickname;
    @BindView(R2.id.sex)
    TextView mSexTv;
    @BindView(R2.id.email)
    EditText mEmail;
    @BindView(R2.id.clear)
    ImageView clear;
    @BindView(R2.id.sex_layout)
    LinearLayout sexLayout;
    @BindView(R2.id.phone_num)
    TextView phoneNum;

    private UserInfoPresenter mPresenter;

    private String sex;

    private String[] mSex = {"男", "女", "保密"};

    private int mSexIndex = 0;

    private Bitmap bitmap;

    private RequestOptions options;

    private boolean isChange = false;

    private boolean isHeadChanged = false;

    private LoadingDialog.Builder builder;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.login_activity_userinfo;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new UserInfoPresenter(this);
        initView();
    }

    @Override
    protected void setListener() {
        setListeners();
    }


    /**
     * 初始化
     */
    private void initView() {
        title.setText("编辑资料");
        String nickName = CommonUtils.getInstance().getNickName();
        nickname.setText(nickName);
        String sex = CommonUtils.getInstance().getSex();
        //性别选择
        switch (sex) {
            case "C":
                sex = "保密";
                break;
            case "F":
                sex = "女";
                break;
            case "M":
                sex = "男";
                break;
            default:
                sex = "保密";
                break;
        }
        mSexTv.setText(sex);

        String email = CommonUtils.getInstance().getEmail();
        if (StringUtils.isNotEmpty(email)) {
            mEmail.setHint(email);
        }

        String phone = CommonUtils.getInstance().getUserName();
        if (StringUtils.isNotEmpty(phone)) {
            phoneNum.setText(StringUtils.encodePhoneNum(phone));
        }

        options = new RequestOptions()
                .circleCrop()
                .placeholder(R.drawable.comment_head_default)
                .error(R.drawable.comment_head_default)
                .priority(Priority.HIGH);
        String headicon = CommonUtils.getInstance().getUserLogo();
        Glide.with(this)
                .load(headicon)
                .apply(options)
                .into(headIcon);


        builder = new LoadingDialog.Builder(UserInfoActivity.this);
        builder.setTitle("提交中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);

    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //清除邮箱
        clear.setOnClickListener(v -> {
            mEmail.setText("");
            clear.setVisibility(View.GONE);
        });

        //返回
        back.setOnClickListener(v -> finish());

        //头像点击
        headIcon.setOnClickListener(v -> PictureSelector.create(UserInfoActivity.this)
                .openGallery(PictureMimeType.ofImage())//仅图片
                .imageSpanCount(4)//每行显示4张
                .maxSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)//单选
                .isCamera(true)//允许使用相机
                .previewImage(true)//允许预览图片
                .isZoomAnim(true)
                .circleDimmedLayer(false)//圆形裁剪
                .cropWH(80, 80)
                .withAspectRatio(1, 1)
                .freeStyleCropEnabled(true)
                .enableCrop(true)
                .compress(true)
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST));

        //性别选择
        sexLayout.setOnClickListener(v -> {
            String sex = mSexTv.getText().toString();
            int index = 0;
            for (int i = 0; i < mSex.length; i++) {
                if (sex.equalsIgnoreCase(mSex[i])) {
                    index = i;
                    break;
                }
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(UserInfoActivity.this);
            builder.setTitle("请选择性别");
            builder.setSingleChoiceItems(mSex, index, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mSexIndex = which;
                }
            });
            builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mSexTv.setText(mSex[mSexIndex]);
                    dialog.dismiss();
                }
            }).show();
        });

        //邮箱监听
        mEmail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isNotEmpty(s.toString())) {
                    clear.setVisibility(View.VISIBLE);
                }
            }
        });

        //提交
        commit.setOnClickListener(v -> {
            isChange = false;
            builder.show();
            if (isHeadChanged) {
                if (bitmap != null) {
                    String headicon = Base64Parse.bitmapToBase64(bitmap);
                    mPresenter.upLoadHead(headicon);
                } else {
                    builder.dismiss();
                    Toasty.normal(UserInfoActivity.this, "头像上传出错！", Toast.LENGTH_SHORT).show();
                    String headicon = CommonUtils.getInstance().getUserLogo();
                    Glide.with(UserInfoActivity.this)
                            .load(headicon)
                            .apply(options)
                            .into(headIcon);
                    isHeadChanged = false;
                }
            } else {
                if (!mSexTv.getText().toString().equals(sex)) {
                    isChange = true;
                }
                String email = CommonUtils.getInstance().getEmail();
                if (!mEmail.getText().toString().equals(email) && StringUtils.isNotEmpty(mEmail.getText().toString())) {
                    isChange = true;
                    if (!StringUtils.isEmail(mEmail.getText().toString())) {
                        builder.dismiss();
                        Toasty.normal(UserInfoActivity.this, "邮箱格式不正确！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                if (isChange) {
                    String nickName = CommonUtils.getInstance().getNickName();
                    mPresenter.changeInfo(getSex(mSexTv.getText().toString()), mEmail.getText().toString(), nickName);
                } else {
                    builder.dismiss();
                    Toasty.normal(UserInfoActivity.this, "请选择您要修改的信息！", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                if (selectList != null && selectList.size() > 0) {
                    RequestBuilder<Bitmap> requestBuilder = Glide.with(UserInfoActivity.this).asBitmap();
                    requestBuilder.load(selectList.get(0).getCompressPath()).listener(new RequestListener<Bitmap>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                            bitmap = resource;
                            isHeadChanged = true;
                            return false;
                        }
                    }).apply(options).into(headIcon);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 头像上传失败
     *
     * @param msg
     */
    @Override
    public void headError(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        String headicon = CommonUtils.getInstance().getUserLogo();
        Glide.with(UserInfoActivity.this)
                .load(headicon)
                .apply(options)
                .into(headIcon);
        isHeadChanged = false;
    }

    /**
     * 头像上传成功
     */
    @Override
    public void headSuccess() {
        if (isChange) {
            String nickName = CommonUtils.getInstance().getNickName();
            mPresenter.changeInfo(getSex(mSexTv.getText().toString()), mEmail.getText().toString(), nickName);
        } else {
            String userName = CommonUtils.getInstance().getUserName();
            mPresenter.getUserInfo(userName);
        }
    }

    /**
     * 修改信息失败
     *
     * @param msg
     */
    @Override
    public void changeError(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 修改信息成功
     */
    @Override
    public void changeSuccess() {
        builder.setTitle("更新信息...");
        String userName = CommonUtils.getInstance().getUserName();
        mPresenter.getUserInfo(userName);
    }

    /**
     * 获取用户信息成功
     *
     * @param bean
     */
    @Override
    public void userInfoSuccess(UserInfoBean bean) {
        builder.dismiss();
        Toasty.normal(this, "信息修改成功！", Toast.LENGTH_SHORT).show();
        if (StringUtils.isEmpty(bean.getNickName())) {
            CommonUtils.getInstance().putConfigData(AppConfigConstant.NICK_NAME, bean.getUsername().replace(bean.getUsername().substring(3, 7), "****"));
        } else {
            CommonUtils.getInstance().putConfigData(AppConfigConstant.NICK_NAME, bean.getNickName());
        }
        CommonUtils.getInstance().putConfigData(AppConfigConstant.USER_NAME, bean.getUsername());
        CommonUtils.getInstance().putConfigData(AppConfigConstant.HEAD_ICON, bean.getLogo());
        CommonUtils.getInstance().putConfigData(AppConfigConstant.EMAIL, bean.getEmail());
        CommonUtils.getInstance().putConfigData(AppConfigConstant.USER_CHECK, bean.getChecked());
        CommonUtils.getInstance().putConfigData(AppConfigConstant.USER_CHECK_REASON, bean.getFailReason());
        String sex;
        if (StringUtils.isEmpty(bean.getSex())) {
            sex = "C";
        } else {
            sex = bean.getSex();
        }
        CommonUtils.getInstance().putConfigData(AppConfigConstant.SEX, sex);
        CommonUtils.getInstance().putConfigData(AppConfigConstant.PHONE_NUM, bean.getTelphone());
        Hawk.put("login", bean);
        BusFactory.getBus().postSticky(new Event.LoginMessage(true));
        finish();

    }

    /**
     * 获取用户信息失败
     *
     * @param msg
     */
    @Override
    public void userInfoError(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
    }

    private String getSex(String sex) {
        String upSex;
        switch (sex.trim()) {
            case "男":
                upSex = "M";
                break;
            case "女":
                upSex = "F";
                break;
            case "保密":
                upSex = "C";
                break;
            default:
                upSex = "C";
        }
        return upSex;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("资料编辑");
        MobclickAgent.onResume(this);
    }


    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("资料编辑");
        MobclickAgent.onPause(this);
    }
}
